<?php
/**
 * Created by PhpStorm.
 * User: Sojo
 * Date: 2017/5/31
 * Time: 17:36
 */
namespace App\Api\Service\Product\Controllers;


use App\Eloquent\Ygt\CategoryFields;
use App\Eloquent\Ygt\DepartmentUser;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\Product;
use App\Engine\Func;
use App\Eloquent\Ygt\ProductFields;
use App\Engine\Product as EngineProduct;

class IndexController extends Controller
{
    public $userId      = 25;
    //进入创建材料页面
    public function goCreate()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        //$userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $categoryId         = request('id',0);
        if(!$userId || !$categoryId)
        {
            xThrow( ERR_PARAMETER );
        }
        $fieldsList         = CategoryFields::getFieldListByType($categoryId);
        $lists              = [];
        foreach($fieldsList as $key=>$val)
        {
            $temp           = [
                'id'=>$val['id'],
                'field_name'=>$val['field_name'],
                'unit'=>$val['field_unit'],
                'is_must'=>$val['is_must'],
            ];
            $lists[]        = $temp;
        }
        $result             = ['cate_fields_arr'=>$lists];
        return $result;
    }
    //创建材料
    public function create()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userId || !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $productName        = request('product_name','');
        $unit               = request('unit','');
        $categoryId         = request('category_id',0);
        $imgId              = request('img_id',0);
        $placeName          = request('place_name','');
        $productNo  = request('product_no');

        $productNo = $productNo ? $productNo : EngineProduct::createAssemblageMaterialNo();

        if(!$productName)
        {
            xThrow(ERR_UNKNOWN,'请填写材料名称');
        }

        //新增属性-计量属性 20181106 zhuyujun
        $measurementAttribute  = request('measurement_attribute');

        //预警数量跟充足数量需要同时有值或同时无值
        $warningNumber      = request('warning_number',0);
        $fullNumber         = request('full_number',0);
        $warningNumber      = intval($warningNumber);
        $fullNumber         = intval($fullNumber);
        if($warningNumber>0 && $fullNumber==0)
        {
            xThrow( ERR_PARAMETER,'库存充足数量未填写' );
        }

        //分类自定义的属性
        $cateFieldsJson     = request('cate_fields_arr','');
        $cateFieldsArr      = [];
        if($cateFieldsJson)
        {
            $cateFieldsArr  = json_decode(htmlspecialchars_decode($cateFieldsJson), true);
        }
        //自定义的属性
        $customJson         = request('custom_arr','');
        $customArr          = [];
        if($customJson)
        {
            $customArr      = json_decode(htmlspecialchars_decode($customJson), true);
        }
        $imgId              = intval($imgId);
        $categoryId         = intval($categoryId);
        //一些必填字段
        $requestMustArr     = [
            'product_name'=>'材料名称不能为空',
            'unit'=>'库存单位',
            'category_id'=>'分类名称',
        ];
        $requestData            = request()->all();
        foreach($requestMustArr as $key=>$val)
        {
            if(!isset($requestData[$key]) || empty($requestData[$key]))
            {
                $requestMustMsg     = $val;
                xThrow( ERR_PARAMETER,$requestMustMsg );
            }
        }
        //过滤分类自定义属性的必填选项
        $cateMustResult         = true;
        $cateMustMessage        = '';
        foreach ($cateFieldsArr as $key=>$val)
        {
            if($cateMustResult === false)
            {
                break;
            }
            $valFieldName       = $val['field_name'];
            $valFieldValue      = $val['field_value'];
            $valIsMust          = $val['is_must'];
            if($valIsMust == 1 && empty($valFieldValue))
            {
                $cateMustResult     = false;
                $cateMustMessage    .= $valFieldName.'必填';
            }
        }
        if(!$cateMustResult)
        {
            xThrow( ERR_PARAMETER,$cateMustMessage );
        }
        //过滤自定义属性的必填选项
        $isMustResult           = true;
        $isMustMessage          = '';
        foreach ($customArr as $key=>$val)
        {
            $valType            = $val['type'];//1标准,2非标
            $valFieldName       = $val['field_name'];
            $valIsMust          = $val['is_must'];
            $valFieldValue      = isset($val['field_value']) ? $val['field_value'] : '';
            $valMinValue        = isset($val['min_value']) ? intval($val['min_value']) : 0;
            $valMaxValue        = isset($val['max_value']) ? intval($val['max_value']) : 0;
            if($valIsMust == 1)
            {
                switch ($valType)
                {
                    case 1:
                        if($valFieldValue == '')
                        {
                            $isMustResult   = false;
                            $isMustMessage  .= $valFieldName.'必填';
                        }
                        break;
                    case 2:
                        if($valMinValue == '' || $valMaxValue == '')
                        {
                            $isMustResult   = false;
                            $isMustMessage  .= $valFieldName.'必填';
                        }
                        break;
                    default:
                }
            }
        }
        if(!$isMustResult)
        {
            xThrow( ERR_PARAMETER,$isMustMessage );
        }
        //exit('xx');
        $companyId          = $userInfo->company_id;
        $data               = request()->all();


        //取消限制 20181110
//        //限制创建同名材料集合
//        $existCount = \App\Eloquent\Ygt\AssemblageMaterial::where(['product_name'=>$productName])->count();
//        if($existCount){
//            xThrow( ERR_PARAMETER,'材料名称已存在' );
//        }

        ////限制同分类下，基本属性不能都相同
        $curFieldsList = array_merge($cateFieldsArr,$customArr);
        //获取同分类下其他材料集合
        $tmpAssemblageMaterialIdArr = \App\Eloquent\Ygt\AssemblageMaterial::where(['category_id'=>$categoryId])->get()->pluck('id');
        $tmpProductFieldsList = \App\Eloquent\Ygt\ProductFields::whereIn('assemblage_material_id',$tmpAssemblageMaterialIdArr)->get()->toArray();
        $tmpProductFieldsDealList = [];
        foreach ($tmpProductFieldsList as $tmpProductFieldsRow){
            $tmpProductFieldsDealList[$tmpProductFieldsRow['assemblage_material_id']][] = $tmpProductFieldsRow;
        }

        //进行比较
        foreach ($tmpProductFieldsDealList as $assemblageMaterialId => $tmpFieldsList){
            $tmpCurFieldsList = $curFieldsList;//用于匹配

            $isSame = false;//是否属性相同
            $isBreak = false;
            $tmp1 = $tmpCurFieldsList;
            $tmp2 = $tmpFieldsList;

            foreach ($tmpCurFieldsList as $k => $v){
                //如果是计量属性，不进行比较
                if($v['is_compute'] == 1){
                    unset($tmp1[$k]);
                    continue;
                }

                foreach ($tmpFieldsList as $kk => $vv){
                    //如果是计量属性，不进行比较
                    if($vv['is_compute'] == 1){
                        unset($tmp2[$kk]);
                        continue;
                    }

                    if($v['field_name'] == $vv['field_name']){
                        $v['min_value'] = isset($v['min_value']) ? $v['min_value'] : 0;
                        $v['max_value'] = isset($v['max_value']) ? $v['max_value'] : 0;
                        if( ($v['field_value'] == $vv['varchar']) && ($v['min_value'] == $vv['min_value']) && ($v['max_value'] == $vv['max_value'])){
                            $isSame = true;
                            //处理其他值相同，但有多一个或者少一个的情况
//                            unset($tmpCurFieldsList[$k]);
//                            unset($tmpFieldsList[$kk]);
                            unset($tmp1[$k]);
                            unset($tmp2[$kk]);
                        }else{
                            //如果值不同，直接跳出，不再进行之后的匹配
                            $isSame = false;
                            $isBreak = true;
                            break;
                        }
                    }
                }
                //如果值不同，直接跳出，不再进行之后的匹配
                if($isBreak){
                    break;
                }
            }

            $tmpCurFieldsList = $tmp1;
            $tmpFieldsList = $tmp2;


            if($isSame){
                if( (empty($tmpCurFieldsList)) && (empty($tmpCurFieldsList)) ){
                    //判断为重复
                    return [
                        'code' => 1,
                        'message' => '已存在相同属性的材料',
                    ];
                }
            }
        }


        //限制
        $existCount = \App\Eloquent\Ygt\AssemblageMaterial::where(['product_no'=>$productNo])->count();
        if($existCount){
            xThrow( ERR_PARAMETER,'材料编号已存在' );
        }

        $tableData          = [
            'product_name'=> $productName,
            'product_no'=> $productNo,
            'unit'=> $unit,
            'img_id'=> $imgId,
            'category_id'=> $categoryId,
            'company_id'=> $companyId,
            'warning_number' => $warningNumber,
            'full_number' => $fullNumber,
            'place_name' => $placeName,
            'measurement_attribute' => $measurementAttribute,
        ];
//        $insertResult       = Product::insertOneData($tableData,'id');

        $tmpObj = \App\Eloquent\Ygt\AssemblageMaterial::firstOrNew(['id'=>'']);
        $tmpObj->fill($tableData);
        $tmpObj->save();
        $insertResult = $tmpObj->id;

        if(!$insertResult)
        {
            xThrow( ERR_UNKNOWN );
        }
        $productId              = $insertResult;

        //添加材料的自定义属性,包含材料自身自定义的和其所属分类自定义的
        //分类的自定义属性
        if(!empty($cateFieldsArr))
        {
            $tableDataList          = [];
            foreach ($cateFieldsArr as $key=>$val)
            {
                $valFieldName       = $val['field_name'];
                $valIsMust          = $val['is_must'];
                $valUnit            = isset($val['unit']) ? $val['unit'] : '';
                $valFieldValue      = isset($val['field_value']) ? $val['field_value'] : '';
                $valMinValue        = isset($val['min_value']) ? intval($val['min_value']) : 0;
                $valMaxValue        = isset($val['max_value']) ? intval($val['max_value']) : 0;
                $valIsCompute          = isset($val['is_compute']) ? $val['is_compute'] : '';
                $temp               = [
                    'assemblage_material_id'=> $productId,
                    'type'=> 1,
                    'field_type'=> 1,
                    'varchar'=> $valFieldValue,
                    'field_name'=> $valFieldName,
                    'min_value'=> $valMinValue,
                    'max_value'=> $valMaxValue,
                    'is_must'=> $valIsMust,
                    'is_compute'=> $valIsCompute,
                    'unit'=>$valUnit,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ];
                $tableDataList[]    = $temp;
            }
            \DB::table('ygt_product_fields')->insert($tableDataList);
        }
        //材料自身自定义字段
        if(!empty($customArr))
        {
            $tableDataList          = [];
            foreach ($customArr as $key=>$val)
            {
                $valType            = $val['type'];
                $valUnit            = isset($val['unit']) ? $val['unit'] : '';
                $valFieldName       = $val['field_name'];
                $valIsMust          = $val['is_must'];
                $valFieldValue      = isset($val['field_value']) ? $val['field_value'] : '';
                $valMinValue        = isset($val['min_value']) ? intval($val['min_value']) : 0;
                $valMaxValue        = isset($val['max_value']) ? intval($val['max_value']) : 0;
                $valIsCompute          = isset($val['is_compute']) ? $val['is_compute'] : '';
                if($valType == 1)
                {
                    $valMinValue    = $valMaxValue = '';
                }
                $temp               = [
                    'assemblage_material_id'=> $productId,
                    'type'=> $valType,
                    'field_type'=> 1,
                    'varchar'=> $valFieldValue,
                    'field_name'=> $valFieldName,
                    'min_value'=> $valMinValue,
                    'max_value'=> $valMaxValue,
                    'is_must'=> $valIsMust,
                    'is_compute'=> $valIsCompute,
                    'unit'=>$valUnit,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ];
                $tableDataList[]    = $temp;
            }
            \DB::table('ygt_product_fields')->insert($tableDataList);
        }

        //新增返回部分材料信息，用于直接创建sku材料 20181113 zhuyujun
        //获取图片ID对应的图片地址
        $imgPath = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($imgId);
        $productInfo = [
            'id' => $productId,
            'product_name' => $productName,
            'warning_number' => $warningNumber,
            'full_number' => $fullNumber,
            'image_path' => $imgPath,
            'img_id' => $imgId,
            'unit' => $unit,
            'custom_fields' => array_merge($cateFieldsArr,$customArr),
        ];


        /**添加新材料时如果这个材料的分类在供应商主营材料分类里，自动关联关系**/
        $needCategoryIdArr = [];
        $productCategoryId = $categoryId;
        $needCategoryIdArr[] = $productCategoryId;
        //获取分类是否有父ID
        $tmpCategoryRow = \App\Eloquent\Ygt\Category::where(['id'=>$productCategoryId])->first();
        if($tmpCategoryRow){
            if($tmpCategoryRow['pid'] && (!in_array($tmpCategoryRow['pid'],[1,2]))){
                $needCategoryIdArr[] = $tmpCategoryRow['pid'];
            }
        }

        //添加主营材料给供应商
        $sellerCompanyList = \App\Eloquent\Ygt\SellerCompany::where(['company_id'=>$tmpCategoryRow['company_id']])->get();
        foreach ($sellerCompanyList as $sellerCompanyRow){
            if($sellerCompanyRow['main_product']){
                $mainProductArr = explode(',',$sellerCompanyRow['main_product']);
                foreach ($mainProductArr as $mainProductId){
                    if(in_array($mainProductId,$needCategoryIdArr)){
                        //添加关系
                        $tmpObj = \App\Eloquent\Ygt\SellerCompanyMaterial::firstOrNew(['seller_company_id'=>$sellerCompanyRow['id'],'assemblage_material_id'=>$productId]);
                        $tmpObj->seller_company_id = $sellerCompanyRow['id'];
                        $tmpObj->assemblage_material_id = $productId;
                        $tmpObj->save();
                    }
                }

            }
        }


        $result         = ['message'=>'创建成功','product_id'=>$productId,'product_info'=>$productInfo];
        return $result;
    }
    public function preAdd()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $type               = request('type',1);//1产品id,2分类id
        $typeId             = request('type_id',0);
        if(!$userId || !$type || !$typeId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $product            = $productFieldsList  = $categoryFieldsList = [];
        $basicArr           = $nonArr = [];
        if($type==2){
            $categoryId     = $typeId;
        }else{
            $productId      = $typeId;
            $where          = [
                'ygt_product.company_id'=>$companyId,
                'ygt_product.id'=>$productId
            ];
            $product        = Product::getJoinInfo($where);
            if(!$product)
            {
                xThrow( ERR_PARAMETER );
            }
            $imgId              = $product->img_id;
            $imgUrl             = Func::getImgUrlById($imgId);
            $product->img_url  = $imgUrl;
            $product->img_path  = $imgUrl;
            if( is_null($product->customer_name))
            {
                $product->customer_name     = '';
            }
            $categoryId         = $product->category_id;
            $where              = ['product_id'=>$productId];
            $fields             = 'id as pfid,field_name,field_type,varchar,numerical,type,min_value,max_value,unit';
            $productFieldsList  = ProductFields::getList($where,$fields)->toArray();
            foreach($productFieldsList as $key=>$val)
            {
                $temp           = $val;
                $valType        = $val['type'];
                $valFieldType   = $val['field_type'];
                $valMinValue    = $val['min_value'];
                $valMaxValue    = $val['max_value'];
                if($valFieldType == 12){
                    $fieldValue = strval($val['numerical']);
                }else{
                    $fieldValue = strval($val['varchar']);
                }
                $temp['field_value']    = $fieldValue;
                if($valType == 2){
                    $placeholder              = $valMinValue.'到'.$valMaxValue.'之间';
                    $temp['placeholder']    = $placeholder;
                    $nonArr[]       = $temp;
                    $temp['placeholder']    = '';
                }else{
                    $temp['placeholder']    = '';
                }
                $basicArr[]               = $temp;
            }
        }
        //$categoryFieldsList     = CategoryFields::getFieldListByType($categoryId);
        $result                 = [
            'product'=>$product,
            'basic_arr'=>$basicArr,
            'non_arr'=>$nonArr,
            'category_fields_list'=>$categoryFieldsList
        ];
        return $result;
    }
    public function detail()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $productId          = request('product_id');
        if(!$userInfo || !$productId)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId,'user_id'=>$userId];
        $departmentUser     = \App\Eloquent\Ygt\DepartmentUser::getInfo($where);
        $privilegeId        = $departmentUser->privilege_id;
        $isSale             = \App\Eloquent\Ygt\Privilege::getAppnodeId( $privilegeId, 10 );//是否采购员
        $printButton        = 1;
        if($isSale)
        {
            $printButton    = 0;
        }
        $where              = ['id'=>$productId];
        $columns            = 'id,product_name,product_no,number,spec';
        $info               = Product::getInfo($where,$columns);
        if(!$info)
        {
            xThrow( ERR_PARAMETER );
        }
        $data               = [
            ['field_name'=>'数量','field_value'=>$info->number],
        ];
        //材料基本属性的自定义字段
        $where              = ['product_id'=>$productId];
        $columns            = 'id,field_name,field_type,varchar,unit,numerical';
        $customFields       = ProductFields::getList($where,$columns,'','',['id','asc'])->toArray();
        foreach($customFields as $key=>$val)
        {
            if($val['field_type'] == 1){
                $fieldValue = $val['varchar'];
            }else{
                $fieldValue = $val['numerical'];
            }
            $fieldValue     = $fieldValue.$val['unit'];
            $data[]         = ['field_name'=>$val['field_name'],'field_value'=>$fieldValue];
        }
        $imgUrl             = url('api/service/common/qrcode?type=1&id='.$productId);
        $result             = [
            'title'=>'材料','data'=>$data,'img_url'=>$imgUrl,'print_button'=>$printButton
        ];
        return $result;
    }

}



















